package com.ta.gulimall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ta.gulimall.product.service.AttrService;
import com.ta.gulimall.product.view.entity.AttrEntity;
import com.ta.gulimall.product.view.pto.SpuDto;
import com.ta.gulimall.product.view.vo.BaseAttrs;
import com.ta.gulimall.product.view.vo.SpuGroupBaseAttrVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ta.gulimall.product.dao.ProductAttrValueDao;
import com.ta.gulimall.product.view.entity.ProductAttrValueEntity;
import com.ta.gulimall.product.service.ProductAttrValueService;
import org.springframework.transaction.annotation.Transactional;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Autowired
    AttrService attrService;
    @Override
    public void saveProductAttrs(SpuDto spuDto, List<BaseAttrs> baseAttrs) {
        if (CollUtil.isEmpty(baseAttrs)) {
            throw new RuntimeException("规格参数是空的");
        }
        List<Long> attrIds = baseAttrs.stream().map(BaseAttrs::getAttrId).collect(Collectors.toList());
        Map<Long, String> map = attrService.listByIds(attrIds).stream().collect(Collectors.toMap(AttrEntity::getAttrId, AttrEntity::getAttrName));

        List<ProductAttrValueEntity> attrs = baseAttrs.stream().map(m -> {
            return BeanUtil.copyProperties(m, ProductAttrValueEntity.class).setSpuId(spuDto.getSpuId()).setAttrName(map.get(m.getAttrId())).setAttrValue(m.getAttrValues());
        }).collect(Collectors.toList());

        this.saveBatch(attrs);
    }

    @Override
    public List<ProductAttrValueEntity> listSpuAttr(Long spuId) {
        LambdaQueryWrapper<ProductAttrValueEntity> wrapper = new LambdaQueryWrapper<ProductAttrValueEntity>()
                .eq(ProductAttrValueEntity::getSpuId, spuId);

        return list(wrapper);
    }

    @Override
    @Transactional
    public void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> entities) {
        remove(new LambdaQueryWrapper<ProductAttrValueEntity>().eq(ProductAttrValueEntity::getSpuId, spuId));


        List<ProductAttrValueEntity> collect = entities.stream().map(m -> m.setSpuId(spuId)).collect(Collectors.toList());
        saveBatch(collect);
    }

    @Override
    public List<SpuGroupBaseAttrVo> listBaseAttrsWithGroup(Long spuId, Long catalogId) {
        List<SpuGroupBaseAttrVo> spuGroupBaseAttrVos =  baseMapper.listBaseAttrsWithGroup(spuId, catalogId);

        return spuGroupBaseAttrVos;
    }


}